import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { getToken, setTitle } from '@/libs/util'

Vue.use(Router)
const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== 'login') {
    // 未登录且要跳转的页面不是登录页
    next({
      name: 'login'
    })
  } else if (!token && to.name === 'login') {
    // 未登陆且要跳转的页面是登录页
    next()
  } else if (token && to.name === 'login') {
    // 已登录且要跳转的页面是登录页
    next({
      name: 'home'
    })
  } else {
    /**
     * 如果路由为空则先获取路由
     */
    if ((store.state.app.routers).length <= 0 && token) {
      store.dispatch('getRouters').then(() => {
        next()
      })
    } else {
      next()
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
